﻿using Microsoft.Extensions.Hosting;
using Microsoft.SqlServer.Management.SqlParser.Parser;
using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace FreeSqlTest.BackgroundServices;

public class SqlParserTestService  : BackgroundService
{





    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var sqlText = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sql1.sql"));
        var parseResult = Parser.Parse(sqlText);


        ErgodicParse(sqlText);
        // foreach (var batch in parseResult.Script.Batches)
        // {
        //     foreach (var statement in batch.Statements)
        //     {
        //         switch (statement)
        //         {
        //             case SqlSelectStatement selectStatement:
        //                 ProcessSelectStatement(selectStatement);
        //                 break;
        //             default:
        //
        //                 Console. WriteLine("Unsupported statment. Printing inner XML");
        //                 Console.WriteLine(statement.Xml);
        //                 break;
        //         }
        //     }
        // }
        return Task.CompletedTask;

    }

    public void ErgodicParse(string sqlText)
    {
        var result = Parser.Parse(sqlText);
        Console.WriteLine($"BatchCount :{result.BatchCount}");
        Console.WriteLine($"Sql :{result.Script.Sql}");


        Console.WriteLine("-------------------------------");
        IterateSqlNode(result.Script);



    }
    static void IterateSqlNode(SqlCodeObject sqlCodeObject, int indent=0)
    {
        if (sqlCodeObject.Children == null)
            return;
        foreach (var child in sqlCodeObject.Children)
        {
            Console.WriteLine($"{new string(' ', indent)}Sql:{child.Sql}, Type:{child.GetType().Name}");
            IterateSqlNode(child, indent+2);
        }
    }
    void ProcessSelectStatement(SqlSelectStatement selectStatement)
    {
        var query = (SqlQuerySpecification)selectStatement.SelectSpecification.QueryExpression;
        var selectClause = query.SelectClause;
        Console.WriteLine($"Select columns {string.Join(", ", selectClause.SelectExpressions.Select(_ => _.Sql))}");
        var fromClause = query.FromClause;
        if (fromClause != null)
        {
            Console.WriteLine($"from tables {string.Join(", ", fromClause.TableExpressions.Select(_ => _.Sql))}");
        }

        var whereClause = query.WhereClause;
        if (whereClause != null)
        {
            Console.WriteLine($"where {whereClause.Expression.Sql}");
        }


    }
}
